package com.wangyi.user.service.impl;

import com.wangyi.basic.constant.VerifyConstants;
import com.wangyi.basic.exception.BusinessException;
import com.wangyi.basic.util.MD5Utils;
import com.wangyi.basic.util.StrUtils;
import com.wangyi.org.domain.Employee;
import com.wangyi.org.domain.Shop;
import com.wangyi.org.domain.ShopAuditLog;
import com.wangyi.user.domain.Logininfo;
import com.wangyi.user.domain.User;
import com.wangyi.user.dto.UserDto;
import com.wangyi.user.mapper.LogininfoMapper;
import com.wangyi.user.mapper.UserMapper;
import com.wangyi.user.service.IUserService;
import com.wangyi.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void del(Long id) {
        // 获取登录信息id
        Long logininfo_id = userMapper.loadById(id).getLogininfoId();
        // 删除登录信息对象
        logininfoMapper.remove(logininfo_id);
        // 删除用户信息
        super.del(id);
    }

    @Override
    public void update(User user) {
        // 处理密码和盐值
        // 获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        // 获取登录信息id
        Long logininfo_id = userMapper.loadById(user.getId()).getLogininfoId();
        // 登录信息logininfo：type不修改
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfo_id);

        logininfoMapper.update(logininfo);
        super.update(user);
    }

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        // 1.校验 - 空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("数据不能为空！！！");
        }

        // 2.校验 - 密码一致校验
        if(!password.trim().equals(passwordRepeat.trim())) {
            throw new BusinessException("两次密码不一致！！！");
        }

        // 3.校验 - 验证码是否过期 :  9527:441122222
        Object redisPhoneCode = redisTemplate.opsForValue().get(VerifyConstants.REGISTER_PREFIX + phone);
        if(redisPhoneCode == null) {
            throw new BusinessException("手机验证码已过期！！！");
        }

        // 4.校验 - 验证码是否正确
        if(!redisPhoneCode.toString().split(":")[0].equalsIgnoreCase(phoneCode)) {
            throw new BusinessException("手机验证码错误！！！");
        }

        // 5.添加 - t_logininfo信息
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        // 6.添加 - t_user信息
        // 设置登录信息id
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        // 1.校验 - 空值校验
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("数据不能为空！！！");
        }
        // 2.校验 - 密码一致校验
        if(!password.trim().equals(passwordRepeat.trim())) {
            throw new BusinessException("两次密码不一致！！！");
        }
        // 3.校验 - 邮箱是否注册过
        User user1 = userMapper.loadByEmail(email);
        if (user1 != null) {
            throw new BusinessException("你已经注册，请直接登录，忘记密码请联系管理员！！！");
        }
        // 4.添加 - t_logininfo信息
        User user = userDto22User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        // 5.添加 - t_user信息
        // 设置登录信息id
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
        // 6.发送激活邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        // 设置发送方
        helper.setFrom("1400964746@qq.com");
        // 设置主题
        helper.setSubject("用户激活");
        // 设置内容
        helper.setText("<h1>你已成功注册，请及时激活账号！！！</h1>" +
                "<a href='http:// localhost:8080/user/active/"+user.getId()+"'>点击该链接激活</a>",true);
        // 设置收件人
        helper.setTo(user.getEmail());
//        helper.setTo("2330191338@qq.com");
        // 发送
        javaMailSender.send(mimeMessage);
    }


    /**
     * 用户激活
     */
    @Override
    public void goLogin(Long id) throws MessagingException {
        // 1.发送邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        // 设置发送方
        helper.setFrom("1400964746@qq.com");
        // 设置主题
        helper.setSubject("账户激活");
        // 设置内容
        helper.setText("<h1>您的账户激活成功！请直接登录！！</h1>",true);
        // 设置收件人
        User user = userMapper.loadById(id);
        helper.setTo(user.getEmail());
//        helper.setTo("2330191338@qq.com");
        // 发送
        javaMailSender.send(mimeMessage);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        // 设置为用户
        logininfo.setType(1);
        return logininfo;
    }

    private User userDto22User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getEmail());
        user.setEmail(userDto.getEmail());

        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());

        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5Pwd);
        return user;
    }
}

